package utils;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.Observable;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;

import nanoxml.XMLElement;

import commands.Commands;

/**
 * A list of users.
 */
public class UserList extends Observable implements ITransmittable {

	private SortedMap<String, User> userList;

	public UserList () {
		userList = new TreeMap<String, User>(); 
	}
	
	@SuppressWarnings("unchecked")
	public UserList (XMLElement element) {
		this ();	
		Enumeration<XMLElement> e = element.enumerateChildren();
		while (e.hasMoreElements()) {
			XMLElement childMessage = e.nextElement();

			if (childMessage.getName().equals(Commands.USER)) {
				User user = new User (childMessage);
				userList.put (user.getUsername(), user);
			}
		}
	}
	
	
	public void addUser (User user) {

		userList.put (user.getUsername(), user);
		refreshObservers();
	}

	public void removeUser (String username) {
		userList.remove (username);
		refreshObservers();
	}

	public boolean containsUser (String username) {
		return userList.containsKey (username);
	}

	public Vector<String> getUsersNames () {
		return new Vector<String> (userList.keySet());
	}

	public User getUser (String username) {
	    return userList.get(username);
	}

	public int size () {
		return userList.size();
	}

	public String toString () {
	    return userList.keySet().toString();
	}

	public void refreshObservers() {
	    setChanged();
	    super.notifyObservers();
	}

	public String parseToString() {
		return userList.keySet().toString();
	}
	
	@Override
	public XMLElement toXML() {
		XMLElement message = new XMLElement ();
		message.setName(Commands.USER_LIST);
		Set<String> usernames = userList.keySet();	
		Iterator<String> i = usernames.iterator();		
		while (i.hasNext()) {
			User user = userList.get(i.next());
			message.addChild (user.toXML());
		}
		return message;
	}
}
